﻿$.fn.upload = function (options) {
    var self = this;
    self.id = 0;
    var $this = $(self);
    if ($this.size() <= 0) return;
    var fileType = ["aac", "ace", "ai", "ain", "amr", "app", "arj", "asf", "asp", "aspx", "av", "avi", "bin", "bmp", "cab", "cad", "cat",
        "cdr", "chm", "com", "css", "cur", "dat", "db", "dll", "dmv", "doc", "dot", "dps", "dpt", "dwg", "dxf", "emf",
        "eps", "et", "ett", "exe", "fla", "ftp", "gif", "hlp", "html", "htm", "icl", "ico", "img", "inf", "ini", "iso", "jpeg", "jpg", "js",
        "m3u", "max", "mdb", "mde", "mht", "mid", "mov", "mp3", "mp4", "mpeg", "mpg", "msi", "nrg", "ocx", "ogg", "ogm", "pdf", "png", "pot", "ppt", "psd", "pub", "qt",
        "ra", "ram", "rar", "rm", "rmvb", "rtf", "rtf", "swf", "tar", "tif", "tiff", "txt", "unknown", "url", "vbs", "vsd", "vss", "vst", "wav", "wave", "wm",
        "wma", "wmd", "wmf", "wmv", "wps", "wpt", "xls", "xlt", "xml", "zip"];
    var defaults = {
        maxsize: 2147483647,
        readonly: false
    };
    $.extend(defaults, options);

    var create=function () {
        self.label = $this.attr("label");//按钮文字
        self.path = $this.attr("path");//图片存储路径
        self.src = $this.attr("action");//调用的上传方法
        self.for = $this.attr("name");//name
        self.callback = $this.attr("callback");//回调函数
        self.accept = $this.attr("filetype");//上传的图片格式
        self.ischangeupload =parseInt($this.attr("ischangeupload"));
        self.classname = $this.attr("classname");//样式的类名称
        self.uploadtype = parseInt($this.attr("uploadtype")) || 1;//上传方式
        self.imagesrc = $this.attr('imagesrc') || "/Images/bg_no_image.gif";
            
        self.files = {};

        if (self.uploadtype == 1) {
            createAddFileBtn();
        } else {
            createAddImageBtn();
            $this.addClass(self.classname);
        }
        
        if (!self.ischangeupload) {
            createUploaddetail();
        }
    };
    var showUploadFile = function () {
        if (self.uploadfile.find('.file').size() > 0) {
            var offset = self.addFileBtn.offset();
            var btnheight = self.addFileBtn.outerHeight();
            self.uploaddetail.show().css({ "position": "absolute", "top": (offset.top + btnheight) + "px", "left": offset.left + "px" });
        }
    };
    var createAddFileBtn=function () {
        if (self.classname) {
            $('<a href="javascript:void(0)" class="btn ' + self.classname + '">' + self.label + '</a>').appendTo($this);
        } else {
            $('<a href="javascript:void(0)" class="btn l-btn-blue">+' + self.label + '</a>').appendTo($this);
        }
        var $inputfile = $('<div class="inputfile"></div>').appendTo($this);
        self.addFileBtn = $('<input type="file" multiple />').appendTo($inputfile).attr("accept", self.accept || "*");
        self.hiddenValue = $('<input type="hidden" name="' + self.name + '" />').appendTo($this);
        self.addFileBtn.bind("change", function () {
            var $this = $(this);
            var files = $this[0].files;
            for (var i = 0, max = files.length; i < max; i++) {
                var d = files[i];
                if (!filesAdd(d)) {
                    continue;
                }
            }

            if (files.length && self.ischangeupload) {
                upload();
            }
        });
    };
    var createAddImageBtn=function () {
        $('<img src="' + self.imagesrc + '"  title="' + self.label + '"/>').appendTo($this);
        if (defaults.readonly) return;
        var $inputfile = $('<div class="inputfile"></div>').appendTo($this);
        self.addFileBtn = $('<input type="file" multiple />').appendTo($inputfile).attr("accept", self.accept || "*");
        self.hiddenValue = $('<input type="hidden" name="' + self.name + '" value="' + self.imagesrc + '"/>').appendTo($this);
        self.addFileBtn.bind("change", function () {
            var $this = $(this);
            var files = $this[0].files;
            for (var i = 0, max = files.length; i < max; i++) {
                var d = files[i];
                if (!filesAdd(d)) {
                    continue;
                }
            }

            if (files.length && self.ischangeupload) {
                upload();
            }
        });
    };
    var upload=function () {
        var data = new FormData();
        data.append("path", self.path);
        var i = 0;
        for (var k in self.files) {
            data.append("files" + i, self.files[k]);
            i++;
        }
        if (i == 0) return;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', self.src, true);
        xhr.onload = function (e) {
            if (this.status == 200) {
                if (self.uploadtype == 1) {
                    if (self.uploaddetail) {
                        self.uploaddetail.hide();
                        self.uploadfile.html("");
                    }
                    self.files = {};
                    if (self.callback) {
                        window[self.callback] && window[self.callback](JSON.parse(e.currentTarget.responseText));
                    }
                } else {
                    self.files = {};
                    var item = JSON.parse(e.currentTarget.responseText);
                    $(self.element).find('img').attr('src', item.result);
                    $(self.element).find('input[type=hidden]').val(item.result);
                }
            }
        };
        xhr.send(data);
    };
    
    var createUploaddetail=function () {
        self.uploaddetail = $('<div class="uploaddetail"></div>').appendTo('body').uniqueId().hide();
        //this.form = $("<form></form>").appendTo(uploaddetail).hide();
        //this.fileinput = $("<input type='file' name='jawsupload' />").appendTo(this.form);
        self.uploadhandel = $('<div class="uploadhandle"></div>').appendTo(self.uploaddetail);

        self.uploadbtn = $('<a href="javascript:void(0)" class="btn l-btn-blue">开始上传</a>').appendTo(self.uploadhandel);
        self.uploadcancel = $('<a href="javascript:void(0)" class="btn l-btn-gray">取消上传</btn>').appendTo(self.uploadhandel);

        self.processbar = $('<span class="processbar"></span>').appendTo(self.uploadhandel);
        self.process = $('<span class="process"></span>').appendTo(self.processbar);

        self.viewmodel = $('<span class="viewmodel"></span>').appendTo(self.uploadhandel);
        self.pic = $('<span class="pic select"></span>').appendTo(self.viewmodel);
        self.list = $('<span class="list"></span>').appendTo(self.viewmodel);

        self.uploadfile = $('<div class="uploadfiles show pic">').appendTo(self.uploaddetail);

        self.uploadfile.on("click", 'span.del', function () {
            var $file = $(this).parent("div.file");
            self._filesDelete($file.find("span.filename").html());
            $file.remove();
        });

        self.uploadbtn.bind("click", function () {
            upload();
        });
        self.uploadcancel.bind("click", function () {
            self.uploaddetail.hide();
            self.uploadfile.html("");
            self.files = {};
        });
        self.pic.bind("click", function () {
            self.list.removeClass("select");
            self.pic.addClass("select");
            self.uploadfile.removeClass("list").addClass("pic");
            showPicModelfiles();
        });
        self.list.bind("click", function () {
            self.pic.removeClass("select");
            self.list.addClass("select");
            self.uploadfile.removeClass("pic").addClass("list");
            showListModelfiles();
        });
    };
    var filesAdd=function (file) {
        if (self.files[file.name]) {
            return false;
        }
        var totalsize = 0;
        for (var i in self.files) {
            totalsize += self.files[i].size;
        }
        if (totalsize + file.size > defaults.maxsize) {
            $.jAlert('上传文件大小超出了最大：' + self.getFileSize(defaults.maxsize));
            return false;
        }
        //验证文件类型liqiang
        var extension = file.name.substr(file.name.lastIndexOf(".") + 1);
        if (!extension || self.accept.indexOf(extension) == -1)
            return false;
            
        self.files[file.name] = file;

        if (!self.ischangeupload) {
            if (self.uploadfile.hasClass('pic') && self.pic.hasClass('select')) {
                appendPicModelfiles(file);
            } else {
                appendListModelfiles(file);
            }
        }
        return true;
    };
    var filesDelete= function (name) {
        self.files[name] = null;
        delete self.files[name];
    };
    var getFileType=function (type, name) {
        if (name) {
            if (name.indexOf('.') != -1) {
                var d = /\.[^\.]+$/.exec(name);
                if (d && d.length > 0) {
                    return d[0].replace('.', '');
                }
            }
        }
        if (type.indexOf('/') != -1) {
            return type.split('/')[1];
        } else {
            return type;
        }
    };
    var getFileSize=function (size) {
        size = parseInt(size);
        if (size <= 0 || size === NaN) {
            return "0 Bytes";
        }
        var kb = Math.round(size / 1024);
        var mb = Math.round(kb / 1024);
        var gb = Math.round(mb / 1024);
        if (gb > 0) {
            return gb + "Gb";
        }
        if (mb > 0) {
            return mb + "Mb";
        }
        if (kb > 0) {
            return kb + "kb";
        }
        return size;
    };
    var appendPicModelfiles= function (d) {
        if (d.type.indexOf('image') != -1) {
            if (typeof (FileReader) != "undefined") {
                var fileReader = new FileReader();
                fileReader.onload = function (e) {
                    var src = e.target.result;
                    $('<div class="file"><i><img src="' + src + '" /></i><span class="filename">' + d.name + '</span><span class="filesize">' + getFileSize(d.size) + '</span><span class="del">x</span></div>').
                        appendTo(self.uploadfile);
                    showUploadFile();
                };
                fileReader.readAsDataURL(d);
            } else {
                $('<div class="file"><i>' + getFileType(d.type, d.name).toUpperCase() + '</i><span class="filename">' + d.name + '</span><span class="filesize">' + getFileSize(d.size) + '</span><span class="del">x</span></div>').
                    appendTo(self.uploadfile);
            }
        } else {
            $('<div class="file"><i>' + getFileType(d.type, d.name).toUpperCase() + '</i><span class="filename">' + d.name + '</span><span class="filesize">' + getFileSize(d.size) + '</span><span class="del">x</span></div>').
                appendTo(self.uploadfile);
        }

        showUploadFile();
    };
    var appendListModelfiles=function (d) {
        var html = [];
        html.push('<div class="file"><i style="background-image: url(/Images/filetype/' + getFileType(d.type, d.name) + '.gif)"></i><span class="filename">' + d.name + '</span><span class="filesize">' + getFileSize(d.size) + '</span><span class="del">x</span></div>');
        self.uploadfile.append(html.join(""));
        showUploadFile();
    };
    var showPicModelfiles= function () {
        uploadfile.html("");
        for (var i in self.files) {
            var d = self.files[i];
            if (d.type.indexOf('image') != -1) {
                var fileReader = new FileReader();
                fileReader.onload = function (e) {
                    var src = e.target.result;
                    $('<div class="file"><i><img src="' + src + '" /></i><span class="filename">' + d.name + '</span><span class="filesize">' + getFileSize(d.size) + '</span><span class="del">x</span></div>').
                        appendTo(self.uploadfile);
                };
                fileReader.readAsDataURL(d);
            } else {
                $('<div class="file"><i>' + getFileType(d.type, d.name).toUpperCase() + '</i><span class="filename">' + d.name + '</span><span class="filesize">' + getFileSize(d.size) + '</span><span class="del">x</span></div>').
                    appendTo(self.uploadfile);
            }
        }
    };
    var showListModelfiles=function () {
        var that = this;
        var html = [];
        for (var i in self.files) {
            var d = self.files[i];
            html.push('<div class="file"><i style="background-image: url(/Images/filetype/' + getFileType(d.type, d.name) + '.gif)"></i><span class="filename">' + d.name + '</span><span class="filesize">' + getFileSize(d.size) + '</span><span class="del">x</span></div>');
        }
        self.uploadfile.html(html.join(""));
    }
    create();
};
$(function () {
    $("div[tag=FileUpload][name][action][path][label]").upload();
});